<template>
  <div>
    <span v-if="!isError">{{ text + loadingText }}</span>
    <span v-else v-html="errText"></span>
  </div>
</template>

<script>
import mixins from '../../mixins'
export default {
  name: 'ssoLogin',
  mixins: [mixins()],
  data () {
    return {
      text: '正在登录中',
      loadingText: '.',
      timer: null,
      query: this.$route.query,
      errText: '',
      isError: false
    }
  },
  created () {
    if (this.timer) {
      this.timer = clearInterval(this.timer)
    }
    this.timer = setInterval(() => {
      this.loadingText.length === 3 ? this.loadingText = '.' : this.loadingText += '.'
    }, 500)

    this.handleLogin({
      grant_type: 'password',
      username: '',
      password: '',
      auth_type: 'xaas-sso',
      token: this.query.access_token,
      sys_id: this.app.ssoAppId
    })
  },
  methods: {
    handleLogin (params) {
      this.$store.dispatch('login', params).then(res => {
        this.$router.push({
          path: '/home'
        })
      }).catch(err => {
        this.isError = true
        if (err.response) {
          if (err.response.data.error_description) {
            this.errText = `登录失败: ${err.response.data.error_description}`
          } else {
            switch (err.response.status) {
              case 500:
                this.errText = '服务器出错!'
                break
              case 504:
                this.errText = '与服务器连接超时!'
                break
              default:
                this.errText = '未知错误!'
                break
            }
          }
        } else {
          this.errText = '与服务器连接超时!'
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
